package com.easy.dev.controller;

import com.easy.dev.entity.Dict;
import com.easy.dev.entity.DictDetail;
import com.easy.dev.entity.TableConfig;
import com.easy.dev.guava.DictCache;
import com.easy.dev.service.impl.BaseServiceImpl;
import com.easy.dev.service.impl.DictDetailServiceImpl;
import com.easy.dev.service.impl.DictServiceImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;

import java.util.*;

@Api(tags = "Dict操作接口")
@RestController
@RequestMapping("/dict")
public class DictController extends BaseController<Dict> {

    @Autowired
    private DictServiceImpl dictService;

    @Autowired
    private DictDetailServiceImpl dictDetailService;

    @Override
    BaseServiceImpl getService() {
        return dictService;
    }

    @GetMapping("/{type}")
    public Map findDictByType(@PathVariable("type")String type){
        Map<String,List<DictDetail>> map = null;
        map = DictCache.dictCache.getIfPresent(type);
        if(map!=null){
            return map;
        }
        DictCache.dictCache.getIfPresent(type);
        List<Dict> list = dictService.findByType(type);
        List<Integer> dictIds = new ArrayList<Integer>(list.size()*2);
        list.forEach(dict -> {
            dictIds.add(dict.getId());
        });
        if (dictIds.size() == 0) {
            return new HashMap();
        }
        List<DictDetail> details = dictDetailService.findByDictIdIn(dictIds);
        //Map<String,List<Dict_detail>> map = new HashMap<String,List<Dict_detail>>();

        Map<String, List<DictDetail>> finalMap = new HashMap<String,List<DictDetail>>();
        list.forEach(dict -> {
            if(finalMap.containsKey(dict.getName())){
                return;
            }
            Iterator<DictDetail> it = details.iterator();
            List<DictDetail> ds = new ArrayList<DictDetail>();
            while(it.hasNext()){
                DictDetail dd = it.next();
                if(dict.getId().equals(dd.getDictId())){
                    dd.setTag(dict.getTag());
                    ds.add(dd);
                    it.remove();
                }
            }
            finalMap.put(dict.getName(),ds);
        });
        DictCache.dictCache.put(type,finalMap);
        return finalMap;
    }

}